<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>学分统计总览</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          icon="el-icon-refresh"
          @click="refreshData"
        >刷新</el-button>
      </div>

      <!-- 查询条件 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <treeselect
            v-model="queryParams.deptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择部门"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-select v-model="queryParams.semester" placeholder="请选择学期" clearable size="small">
            <el-option
              v-for="semester in semesterOptions"
              :key="semester"
              :label="semester"
              :value="semester"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="card-row">
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div slot="header" class="clearfix">
              <span>总用户数</span>
            </div>
            <div class="card-content">
              <div class="card-value">{{ overviewStats.totalUsers || 0 }}</div>
              <div class="card-label">用户</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div slot="header" class="clearfix">
              <span>总学分</span>
            </div>
            <div class="card-content">
              <div class="card-value">{{ overviewStats.totalCredits || 0 }}</div>
              <div class="card-label">学分</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div slot="header" class="clearfix">
              <span>平均学分</span>
            </div>
            <div class="card-content">
              <div class="card-value">{{ overviewStats.averageCredits || 0 }}</div>
              <div class="card-label">学分/人</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="stat-card">
            <div slot="header" class="clearfix">
              <span>本学期总学分</span>
            </div>
            <div class="card-content">
              <div class="card-value">{{ overviewStats.currentSemesterCredits || 0 }}</div>
              <div class="card-label">学分</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>部门学分分布</span>
            </div>
            <div class="chart-container">
              <div ref="deptChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>学分排名 Top 10</span>
            </div>
            <div class="chart-container">
              <div ref="rankChart" style="width: 100%; height: 300px;"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 用户学分表格 -->
      <el-table
        v-loading="loading"
        :data="userCreditList"
        style="width: 100%"
        border
      >
        <el-table-column label="序号" type="index" width="50" align="center" />
        <el-table-column label="用户名称" align="center" prop="userName" :show-overflow-tooltip="true" />
        <el-table-column label="部门" align="center" prop="deptName" :show-overflow-tooltip="true" />
        <el-table-column label="总学分" align="center" prop="totalCredits" sortable />
        <el-table-column label="本学期学分" align="center" prop="currentSemesterCredits" sortable />
        <el-table-column label="活动参与数" align="center" prop="activityCount" sortable />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleViewDetail(scope.row)"
            >查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script>
import { listUser } from "@/api/system/user";
import { listDept } from "@/api/system/dept";
import { getUserCreditStats, getSemesterList, getCurrentSemester } from "@/api/secondclass/credit";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as echarts from 'echarts';

export default {
  name: "CreditOverview",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户学分列表
      userCreditList: [],
      // 部门树选项
      deptOptions: [],
      // 学期选项
      semesterOptions: [],
      // 当前学期
      currentSemester: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        deptId: undefined,
        semester: undefined
      },
      // 总览统计数据
      overviewStats: {
        totalUsers: 0,
        totalCredits: 0,
        averageCredits: 0,
        currentSemesterCredits: 0
      },
      // 部门学分统计
      deptCreditStats: [],
      // 用户学分排名
      userCreditRanking: [],
      // 图表实例
      deptChart: null,
      rankChart: null
    };
  },
  created() {
    this.getDeptTree();
    this.getSemesterOptions();
    this.getCurrentSemester();
    this.getList();
  },
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    if (this.deptChart) {
      this.deptChart.dispose();
    }
    if (this.rankChart) {
      this.rankChart.dispose();
    }
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId", "parentId");
      });
    },
    /** 获取学期选项 */
    getSemesterOptions() {
      getSemesterList().then(response => {
        this.semesterOptions = response.data;
      });
    },
    /** 获取当前学期 */
    getCurrentSemester() {
      getCurrentSemester().then(response => {
        this.currentSemester = response.data;
        this.queryParams.semester = this.currentSemester;
      });
    },
    /** 查询用户学分列表 */
    getList() {
      this.loading = true;
      
      // 查询用户列表
      listUser(this.queryParams).then(response => {
        const userList = response.rows;
        this.total = response.total;
        
        // 初始化统计数据
        this.overviewStats.totalUsers = userList.length;
        this.overviewStats.totalCredits = 0;
        this.overviewStats.currentSemesterCredits = 0;
        
        // 部门学分统计初始化
        this.deptCreditStats = [];
        const deptCredits = {};
        
        // 用户学分列表初始化
        this.userCreditList = [];
        
        // 处理每个用户的学分统计
        const promises = userList.map(user => {
          return getUserCreditStats(user.userId).then(statsResponse => {
            const stats = statsResponse.data;
            const totalCredits = stats.totalCredit || 0;
            const currentSemesterCredits = stats.semesterCredits && stats.semesterCredits[this.currentSemester] 
              ? stats.semesterCredits[this.currentSemester] : 0;
            
            // 累加总学分
            this.overviewStats.totalCredits += parseFloat(totalCredits);
            
            // 累加当前学期学分
            this.overviewStats.currentSemesterCredits += parseFloat(currentSemesterCredits);
            
            // 部门学分统计
            if (user.deptName) {
              if (!deptCredits[user.deptName]) {
                deptCredits[user.deptName] = 0;
              }
              deptCredits[user.deptName] += parseFloat(totalCredits);
            }
            
            // 添加到用户学分列表
            this.userCreditList.push({
              userId: user.userId,
              userName: user.userName,
              deptName: user.deptName,
              totalCredits: totalCredits,
              currentSemesterCredits: currentSemesterCredits,
              activityCount: stats.recordCount || 0
            });
            
            return stats;
          });
        });
        
        // 所有用户学分统计完成后
        Promise.all(promises).then(() => {
          // 计算平均学分
          this.overviewStats.averageCredits = this.userCreditList.length > 0 
            ? (this.overviewStats.totalCredits / this.userCreditList.length).toFixed(2) 
            : 0;
          
          // 处理部门学分统计
          for (const deptName in deptCredits) {
            this.deptCreditStats.push({
              name: deptName,
              value: deptCredits[deptName].toFixed(2)
            });
          }
          
          // 用户学分排名
          this.userCreditRanking = [...this.userCreditList]
            .sort((a, b) => b.totalCredits - a.totalCredits)
            .slice(0, 10);
          
          // 更新图表
          this.updateCharts();
          
          this.loading = false;
        }).catch(() => {
          this.loading = false;
        });
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查看详情按钮操作 */
    handleViewDetail(row) {
      this.$router.push({ 
        path: '/secondclass/credit/stats', 
        query: { userId: row.userId } 
      });
    },
    /** 刷新数据 */
    refreshData() {
      this.getList();
    },
    /** 初始化图表 */
    initCharts() {
      // 初始化部门学分分布图表
      this.deptChart = echarts.init(this.$refs.deptChart);
      
      // 初始化学分排名图表
      this.rankChart = echarts.init(this.$refs.rankChart);
      
      // 设置初始配置
      this.updateCharts();
    },
    /** 更新图表数据 */
    updateCharts() {
      if (!this.deptChart || !this.rankChart) {
        return;
      }
      
      // 更新部门学分分布图表
      this.deptChart.setOption({
        title: {
          text: '部门学分分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.deptCreditStats.map(item => item.name)
        },
        series: [
          {
            name: '部门学分',
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            data: this.deptCreditStats,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
      
      // 更新学分排名图表
      this.rankChart.setOption({
        title: {
          text: '学分排名 Top 10',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '学分'
        },
        yAxis: {
          type: 'category',
          data: this.userCreditRanking.map(user => user.userName),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        series: [
          {
            name: '总学分',
            type: 'bar',
            data: this.userCreditRanking.map(user => user.totalCredits),
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      });
    },
    /** 调整图表大小 */
    resizeCharts() {
      if (this.deptChart) {
        this.deptChart.resize();
      }
      if (this.rankChart) {
        this.rankChart.resize();
      }
    },
    // 转树形结构
    handleTree(data, id, parentId) {
      let config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: 'children'
      };

      var childrenListMap = {};
      var nodeIds = {};
      var tree = [];

      for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
      }

      for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
          tree.push(d);
        }
      }

      for (let t of tree) {
        adaptToChildrenList(t);
      }

      function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
          o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
          for (let c of o[config.childrenList]) {
            adaptToChildrenList(c);
          }
        }
      }
      return tree;
    }
  }
};
</script>

<style scoped>
.card-row {
  margin-bottom: 20px;
}
.chart-row {
  margin-bottom: 20px;
}
.stat-card {
  height: 120px;
}
.card-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}
.card-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}
.chart-container {
  width: 100%;
  height: 300px;
}
</style> 